<template>
	<view class="shopcart-container">
		<view class="cart-content" v-if="cartData.length>0">
			<view class="cart-head flex-sb">
				<view class="total-num">共<text class="num">{{cartData.length}}</text>件商品</view>
				<view class="edit" @click="handleToggleMode">
					<view class="normal" v-if="mode == 'normal'">
						<xs-icon name="icon-bianji"></xs-icon>
						<text class="text">编辑</text>
					</view>
					<view class="edit" v-if="mode == 'edit'">
						<text class="text">完成</text>
					</view>
				</view>
			</view>
			<view class="shop-list">
				<view class="item flex-start" v-for="(item,index) in cartData" :key="index">
					<view class="goods-conetnt flex-start"
					@touchstart="itemTouchStart($event, index)" @touchmove="itemTouchMove($event, index)"
					@touchend="itemTouchEnd($event, index)"  :style="{ marginLeft: touch.index === index ?touch.late + 'px' : 0, transition: 'all 0.4s' }">
						<radio :checked="goodsCheck(item.id,checkedIds)" @click="handleCheckItem(item.id)"></radio>
						<view class="item-image">
							<image class="image" :src="item.goods.image.url" mode="aspectFill"></image>
						</view>
						<view class="item-content" @click="cartLinksGoods(item.goods.goodsId)">
							<view class="item-title">{{item.goods.goodsName}}</view>
							<view v-if="item.goodsSku!=null">
								<view class="specs" v-for="(iv,ind) in goodsSkuProps(item)" :key="ind">{{iv}}</view>
							</view>
							<view class="price-number flex-sb">
								<view class="price">¥<text class="price-num">{{goodsSkuPrice(item)}}</text></view>
								<u-number-box v-model="item.goodsNum" @change="goodsNumChange($event,item)" :min="1"
									:max="100">
									<view slot="minus" class="minus">
										<u-icon name="minus" size="12"></u-icon>
									</view>
									<text slot="input" style="min-width: 20px;text-align: center;"
										class="input">{{item.goodsNum}}</text>
									<view slot="plus" class="plus">
										<u-icon name="plus" color="#FFFFFF" size="12"></u-icon>
									</view>
								</u-number-box>
							</view>
						</view>
					</view>
					<view class="item-delete-goods" @click="handleDeleteCarts(item)">
						<unt-icon name="icon-shanchu" color="#fff" size="30"></unt-icon>
					</view>
				</view>
			</view>
		</view>
		<!-- 空 -->
		<unt-empty type="cart" v-else></unt-empty>
		<!-- 空 -->
		<!-- 商品推荐 -->
		<view class="recommend-content">
			<unt-divider v-show="loveData.length>0">
				<xs-icon name="icon-cainixihuan" color="#01ab36"></xs-icon>
				<text style='color:#01ab36;margin-left: 10rpx;'>猜你喜欢</text>
			</unt-divider>
			<unt-shop-list :data="loveData"></unt-shop-list>
		</view>
		<!-- 商品推荐 -->
		<unt-tab-bar :index="2">
			<!-- 结算start -->
			<view class="settlement flex-sb" v-show="cartData.length>0">
				<radio :checked="checkedIds.length > 0 && checkedIds.length === cartData.length"
					@click="handleCheckAll()"></radio>
				<view class="settlement-total-btn flex-sb">
					<view class="price">合计：<text class="price-accord">¥</text><text
							class="price-num">{{totalPrice}}</text></view>
					<view v-if="mode == 'normal'" class="btn" :class="{ disabled: checkedIds.join() == '' }"
						@click="setTlement()">
						去结算{{ checkedIds.length > 0 ? `(${checkedIds.length})` : '' }}</text></view>
					<view v-if="mode == 'edit'" class="btn" :class="{ disabled: checkedIds.join() == '' }"
						@click="handleDelete()">
						<text>删除</text>
					</view>
				</view>
			</view>
			<!-- 结算end -->
		</unt-tab-bar>
	</view>
</template>

<script>
	import * as Cart from '@/api/cart/index.js'
	import * as Goods from '@/api/goods/index.js'
	export default {
		data() {
			return {
				// 当前模式: normal正常 edit编辑
				mode: 'normal',
				cartData: [],
				checkedIds: [],
				totalPrice: 0,
				loveData: [],
				touch: {
					index: null,
					start: 0,
					end: 0,
					late: 0
				},
				page:{
					pageSize:10,
					pageNum :1
				}
			}
		},
		watch: {
			// 监听选中的商品
			checkedIds: {
				handler(val) {
					// 计算合计金额
					this.onCalcTotalPrice()
				},
				immediate: false
			}
		},
		onShow() {
			this.checkedIds = [];
			this.getCartListData();
			this.refshRecommend();
		},
		methods: {
			refshRecommend(){
				Goods.recommend(this.page).then(res => {
					this.loveData = res.data;
				}).catch()
			},
			cartLinksGoods(id){
				this.$unts.navTo('pages_moon/goods/detail/detail', {
					id: id
				})
			},
			setTlement() {
				if(this.checkedIds.length){
					this.$unts.navTo('pages_moon/checkout/checkout', {
						id: this.checkedIds.toString()
					})
				}
			},
			getCartListData() {
				const userId = this.$store.getters.userId;
				Cart.list({
					page:1,
					pageSize:99900,
					userId: userId
				}).then(res => {
					this.cartData = res.data.records;
				}).catch()
			},
			addCartGoods(id, goodsId, number, skuId = '') {
				const data = {
					id: id,
					goodsId: goodsId,
					goodsSkuId: skuId,
					goodsNum: number
				};
				Cart.edit(data).then(res => {}).catch()
			},
			goodsNumChange(val, item) {
				this.addCartGoods(item.id, item.goodsId, val.value, item.goodsSkuId);
				item.goodsNum = val.value;
				this.onCalcTotalPrice();
			},
			// 切换当前模式
			handleToggleMode() {
				this.mode = this.mode == 'normal' ? 'edit' : 'normal'
			},
			handleCheckItem(cartId) {
				const index = this.checkedIds.findIndex(id => id === cartId);
				index < 0 ? this.checkedIds.push(cartId) : this.checkedIds.splice(index, 1);
			},
			// 全选事件
			handleCheckAll() {
				const {
					checkedIds,
					cartData
				} = this
				this.checkedIds = checkedIds.length === cartData.length ? [] : cartData.map(item => item.id)
			},
			onCalcTotalPrice() {
				const app = this
				// 选中的商品记录
				const checkedList = app.cartData.filter(item => uni.$unt.inArray(item.id, app.checkedIds))
				// 计算总金额
				let tempPrice = 0;
				checkedList.forEach(item => {
					let sku_price = 0;
					if (item.goodsSku !== null) {
						sku_price = item.goodsSku.goodsPrice;
					} else {
						sku_price = item.goods.goodsPriceMin;
					}
					// 商品单价, 为了方便计算先转换单位为分 (整数)
					const unitPrice = sku_price * 100;
					tempPrice += unitPrice * item.goodsNum;
				})
				app.totalPrice = (tempPrice / 100).toFixed(2);
			},
			// 删除选中的商品弹窗事件
			handleDelete() {
				const app = this
				if (!app.checkedIds.length) {
					return false
				}
				uni.showModal({
					title: '友情提示',
					content: '您确定要删除该商品吗？',
					showCancel: true,
					success({
						confirm
					}) {
						// 确认删除
						confirm && app.onClearCart()
					}
				})
			},
			handleDeleteCarts(item){
				Cart.del({
					ids: item.id.toString()
				}).then(res => {
					this.touch.index=null;
					this.$unts.toast(res.message);
					this.getCartListData()
				}).catch()
			},
			// 确认删除商品
			onClearCart() {
				const ids = this.checkedIds;
				Cart.del({
					ids: ids.toString()
				}).then(res => {
					this.$unts.toast(res.message);
					this.getCartListData()
				}).catch()
			},
			// 手指触摸事件
			itemTouchStart(e, i) {
				this.touch.index = i;
				this.touch.start = e.changedTouches[0].pageX;
				// console.log('手指触摸时', this.startX);
			},
			// 手指移动事件
			itemTouchMove(e) {
				let moveX = e.changedTouches[0].pageX;
				this.touch.late = moveX - this.touch.start >= 0 ? 0 : moveX - this.touch.start;
			},
			// 手指离开事件
			itemTouchEnd(e, i) {
				let endX = e.changedTouches[0].pageX;
				// 如果手指离开和手指触摸时的值一致则是点击事件的行为，不以滑动的逻辑处理此行为
				if (endX == this.touch.start) {
					if (this.touch.late !== 0) return (this.touch.late = 0);
					return;
				}
				this.touch.late = endX - this.touch.start;
				this.touch.late= this.touch.late <= -41 ? -60 : 0;
			}
		},
		computed: {
			goodsSkuProps() {
				return function(val) {
					if (val.goodsSku !== null) {
						const name = JSON.parse(val.goodsSku.goodsProps).map((prop) => prop.value.name);
						return name;
					} else {
						return 1;
					}
				}
			},
			goodsSkuPrice() {
				return function(val) {
					if (val.goodsSku !== null) {
						return val.goodsSku.goodsPrice;
					} else {
						return val.goods.goodsPriceMin;
					}
				}
			},
			goodsCheck() {
				return function(val, ids) {
					return uni.$unt.inArray(val, ids);
				}
			}
		},
		/**
		 * 下拉刷新
		 */
		onPullDownRefresh() {
			// 获取首页数据
			this.getCartListData(() => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			this.page.pageSize += 10;
			this.refshRecommend();
		}
	}
</script>

<style lang="scss">
	.shopcart-container {
		position: relative;
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-bottom: 300rpx;

		.cart-content {
			width: 100vw;
			padding: 20rpx;

			.cart-head {
				.total-num {
					font-size: 28rpx;

					.num {
						color: #FC483C;
					}
				}

				.edit {
					.text {
						margin-left: 10rpx;
					}
				}
			}

			.shop-list {
				margin-top: 30rpx;

				.item {
					position: relative;
					padding: 20rpx;
					margin-bottom: 16rpx;
					border-radius: 10rpx;
					box-shadow: 4rpx 4rpx 20rpx #e9ebed, -4rpx -4rpx 20rpx #e9ebed;
					overflow: hidden;
					align-items: stretch;

					.goods-conetnt {
						width: 100%;
						flex-shrink: 0;
					}

					.item-image {
						margin: 0rpx 10rpx;
						width: 200rpx;
						height: 200rpx;
						flex-shrink: 0;

						.image {
							width: 100%;
							height: 100%;
						}
					}

					.item-content {
						width: 100%;
						min-height: 100px;
						display: flex;
						justify-content: space-between;
						flex-direction: column;

						.item-title {
							font-weight: bold;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							overflow: hidden;
							text-overflow: ellipsis;
							font-size: 28rpx;
							margin-bottom: 10rpx;
						}

						.specs {
							display: inline-block;
							border-radius: 10rpx;
							margin: 0px 0px 10rpx 0px;
							padding: 4rpx 10rpx;
							font-size: 24rpx;
							background-color: #F3F3F5;
							margin-right: 15rpx;
						}

						.price-number {
							.price {
								color: #FC483C;

								.price-num {
									font-size: 36rpx;
									font-weight: bold;
								}
							}
						}

						.minus {
							width: 44rpx;
							height: 44rpx;
							border-width: 2rpx;
							border-color: #E6E6E6;
							border-style: solid;
							border-top-left-radius: 200rpx;
							border-top-right-radius: 200rpx;
							border-bottom-left-radius: 200rpx;
							border-bottom-right-radius: 200rpx;
							@include flex;
							justify-content: center;
							align-items: center;
						}

						.input {
							padding: 0 20rpx;
						}

						.plus {
							width: 44rpx;
							height: 44rpx;
							background-color: #01ab36;
							border-radius: 50%;
							/* #ifndef APP-NVUE */
							display: flex;
							/* #endif */
							justify-content: center;
							align-items: center;
						}
					}

					.item-delete-goods {
						flex-grow: 1;
						background: #CC3F20;
						width: 60px;
						display: flex;
						justify-content: center;
						align-items: center;
						margin-left: 20px;
						border-radius: 5px;
					}
				}
			}

			// 
		}

		// 空
		.shop-empty {
			width: 100vw;

			button {
				width: 240rpx;
				margin-top: 40rpx;
			}
		}

		// 
	}

	.u-tabbar--fixed {
		box-shadow: none;
	}

	.settlement {
		width: 100vw;
		position: absolute;
		bottom: 49px;
		left: 0rpx;
		padding: 20rpx;
		box-shadow: 0 -4rpx 20rpx #f2f3f4;
		margin-bottom: constant(safe-area-inset-bottom);
		/*兼容 IOS<11.2*/
		margin-bottom: env(safe-area-inset-bottom);
		background: #fff;

		/*兼容 IOS>11.2*/
		.settlement-total-btn {
			.price {
				margin-right: 10rpx;

				.price-accord {
					color: #FC483C;
				}

				.price-num {
					color: #FC483C;
					font-size: 36rpx;
					font-weight: bold;
				}
			}

			.btn {
				margin-left: 20rpx;
				font-size: 28rpx;
				padding: 10rpx 20rpx;
				border-radius: 100rpx;
				color: #fff;
				background: linear-gradient(to right, #F9271E, #FE5E33);
			}

			.disabled {
				background: #ff9779;
			}
		}
	}
	.recommend-content{
		    padding: 10px;
		    width: 100%;
	}
</style>